package com.example.booklist.service;

import com.example.booklist.mapper.BookInfoMapper;
import com.example.booklist.model.BookInfo;
import com.example.booklist.model.PageRequest;
import com.example.booklist.model.PageResult;
import com.example.booklist.enums.StatusEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class BookService {


    @Autowired
    private BookInfoMapper bookInfoMapper;


    public PageResult<BookInfo> getBookByPage(PageRequest pageRequest) {
        if(pageRequest == null) {
            return null;
        }
        List<BookInfo> books = bookInfoMapper.selectBooksByPage(pageRequest.getPageSize(),pageRequest.getOffset());
        if(books == null) {
            return null;
        }
        //根据状态来设置状态中文码
        for(BookInfo bookInfo : books) {
            bookInfo.setStatusCN(StatusEnum.getStatusByCode(bookInfo.getStatus()).getStatusCN());
        }
        return new PageResult<BookInfo>(books,bookInfoMapper.total(),pageRequest);
    }

    public String setBook(BookInfo bookInfo) {
        if(bookInfo == null) {
            return "添加失败";
        }
        Integer result = bookInfoMapper.insertBook(bookInfo);
        if(result <= 0) {
            return "添加失败";
        }
        return "";
    }

    public void deleteById(BookInfo bookInfo) {
        if(bookInfo.getId() < 0) {
            return;
        }
        Integer result = bookInfoMapper.deleteBookById(bookInfo);
        if(result <= 0) {
            return;
        }
    }

    public void updateBookById(BookInfo bookInfo) {
        if(bookInfo == null) {
            return;
        }
        bookInfoMapper.updateBookById(bookInfo);

    }

    public BookInfo getBookById(Integer id) {
        if(id < 0) {
            return null;
        }
        BookInfo book = bookInfoMapper.selectBookById(id);
        if(book == null) {
            return null;
        }
        return book;
    }

    public void deleteBookBatch(List<Integer> ids) {
        if(ids == null && ids.size() < 1) {
            return;
        }
        Integer result = bookInfoMapper.batchDeleteBook(ids);
        if(result < 1) {
            return;
        }
    }
}
